package lib

import (
	"encoding/json"
	"fmt"
	"strconv"

	//	"reflect"

	redigo "github.com/gomodule/redigo/redis"
)

var RedisPool *redigo.Pool
var RedisCoon redigo.Conn

func init() {
	//config := make(map[string](map[string]interface{}))
	//	json.Unmarshal([]byte(Config), &config)
	config := Config()
	/*
		config := make(map[string](map[string]interface{}))
		config["redis"] = map[string]interface{}{
			"Host":   "127.0.0.1",
			"Port":   "6379",
			"Size":   "2000",
			"Select": "3",
		}
	*/
	redis_host := ((config["redis"]["Host"]).(string)) //"127.0.0.1"
	redis_port, _ := strconv.Atoi((config["redis"]["Port"]).(string))
	redis_pool_size, _ := strconv.Atoi((config["redis"]["Size"]).(string))
	redis_select, _ := strconv.Atoi((config["redis"]["Select"]).(string))
	//6379
	RedisPool = redigo.NewPool(func() (redigo.Conn, error) {
		c, err := redigo.Dial("tcp", fmt.Sprintf("%s:%d", redis_host, redis_port))
		if err != nil {
			return nil, err
		}
		return c, nil
	}, redis_pool_size)
	RedisCoon = RedisPool.Get()
	RedisCoon.Do("SELECT", redis_select)
	//return redigo.Conn
}

//记得销毁本次链连接
//defer RedisCoon.Close()

//redis set操作
func RedisSet(key string, value interface{}, timeout int) (reply interface{}, conn redigo.Conn) {
	if timeout == 0 {
		timeout = 60
	}
	//conn.Do("SELECT", 1)
	//fmt.Printf("a %s=>%T \r\n", value, value)
	//_type := reflect.TypeOf(value)

	var data string

	//if _type == "string" {
	dataType, _ := json.Marshal(value)
	data = string(dataType)
	//data = value
	//}
	/*	else if _type == "[]string" {
			dataType, _ := json.Marshal(param)
			data = string(dataType)

		}
	*/
	//	fmt.Printf("b %s=>%T data %s \r\n", _type, _type, data)

	//记得销毁本次链连接
	//defer conn.Close()

	//fmt.Println(key, timeout)
	//写入数据
	//设置key过期时间
	//  _, err = conn.Do("SET", "mykey", "superWang", "EX", "5")
	//s, _ := redigo.Bytes(value)
	reply, err := RedisCoon.Do("SET", key, data, "EX", timeout)
	if err != nil {
		fmt.Println("err while setting:", err)
		return "", RedisCoon
	}
	return reply, RedisCoon
}

//redis get查询，此处没有把string转成不同的类型，是因为转换的类型太多
func RedisGet(key string) (reply string, conn redigo.Conn) {
	//conn.Do("SELECT", 1)
	//记得销毁本次链连接
	//defer conn.Close()

	//fmt.Println(key, timeout)
	//写入数据
	//设置key过期时间
	//  _, err = conn.Do("SET", "mykey", "superWang", "EX", "5")
	reply, err := redigo.String(RedisCoon.Do("GET", key))
	if err != nil {
		fmt.Println("err while setting:", err)
		return "", RedisCoon
	}
	//fmt.Println("aa:", aa)
	return reply, RedisCoon
	/*
		//var reply map[string]interface{}
		err = json.Unmarshal([]byte(aa), &reply)
		if err != nil {
			fmt.Println("json.Unmarshal error:", err)
		}

		//fmt.Println("reply:", reply)
		return reply, conn
	*/
}
